Script Start
(IP, Port)

Object Sock;		//Sock is the listen socket, and Sock2 is the communicating socket
Object cmd;
U4 event;
String in;
String signature;

StrAssign(signature, IP, ":", Port);

ObjCreateEx(Sock, "QSock");

if (QSO_Socket(Sock, 2, 2, 0))		//The 2, 2, 0 is UDP sock_dgram
{
	PrintLn("Socket command failed");
	return;
}



if (QSO_Bind(Sock, IP, Port))
{
	PrintLn("Bind failed");
	return;
}

//Below are the possible sock event
//	1 Timeout
//	2 User event
//	4 Read
//	8 Write
//	16 Closed
//	32 Accept
//	64 Connect

PrintLn("Socket at ", signature, " is at EID ", QS_EID());
Communicate(Sock, signature);
PrintLn("Socket at ", signature, " has ended");
EndScript

Script Communicate
(Sock, signature)

U4 event;
String s;
Object cmd, o;
U0 actual_sent;
String ip, port;

Again:

if (QSO_Wait(Sock, 4, event))		//4 (read)
{
	PrintLn("Error in QSO_Wait for ", signature);
	return;
}

if (event & 2)		//an external event
{
	while (TaskGet(0, cmd, o, ip, port) == 0)
	{
		switch (cmd)
		{
		case "Send"
			if (QSO_SendTo(Sock, o, ip, port, actual_sent))
			{
				PrintLn("Failed to QSO_Send");
				return;
			}
			PrintLn(signature, ": actual sent is ", actual_sent);
			break;
			
		case "ShutDown"
			if (QSO_ShutDown(Sock, 1))
			{
				PrintLn("Failed to QSO_Shutdown");
				return;
			}
			break;
			
		default
			PrintLn("Ignoring unknown command ", cmd);
			break;
		}
	}
	QSO_ResetUserEvent(Sock);
}

if (event & 4)		//there is data to be read in socket
{
	if (QSO_RecvFrom(Sock, s, 40000, ip, port))		//the 40000 is a number plug from the air
	{
		PrintLn(signature, ": Error in QSO_Communicate");
		return;
	}
	PrintLn(signature, ": Received ", StrLen(s), " bytes from ", ip, ":", port);
	PrintLn(s);
}

goto Again;
EndScript


Script Send
(eid, x, ip, port)
TaskPost(eid, "Send", x, ip, port);
EndScript

Script ShutDown
(eid)
TaskPost(eid, "ShutDown");
EndScript

